/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2022-08-08 09:10:21
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-11-26 13:36:45
 */
import { http } from "./http";
import { useAppStore } from "../store";
import { message } from "ant-design-vue";
import router from "@/routes";
import Nprogress from "nprogress";
import { ref } from "vue";
/**
 * HTTP网络请求全局拦截处理程序
 */
const useInterceptors = function () {
  /**
   * 请求拦截处理
   * @param options
   */
  http.interceptors.request.use((request: any) => {
    // 接口是否使用token，不使用的话在第四个参数中配置"config.headers.useToken = false"
    let useToken: boolean = request?.headers?.useToken === false ? false : true;
    if (!request.headers.Authorization && useToken) {
      const appStore = useAppStore();
      let token = appStore.token;
      if (token && token !== "") {
        request.headers.Authorization = token;
      }
    }
    Nprogress.start();
    request.timeout = 0;
    return request;
  });
  const doneTimeout = ref();
  /**
   * 应答拦截处理
   * @param res
   */
  http.interceptors.response.use(
    (response: any) => {
      if (doneTimeout.value) {
        clearTimeout(doneTimeout.value);
      }
      doneTimeout.value = setTimeout(() => {
        Nprogress.done();
      }, 500);
      if (response && response.status === 200) {
        return response.data;
      } else {
        return response;
      }
    },
    (error: any) => {
      debugger;
      if (doneTimeout.value) {
        clearTimeout(doneTimeout.value);
      }
      doneTimeout.value = setTimeout(() => {
        Nprogress.done();
      }, 500);
      /**
       * 处理规则说明：
       * showAxiosErr=true时处理逻辑
       * 1. 除401和403以外的错误统一显示为网络请求出错了~
       * 2. 401统一为操作权限错误
       * 3. 403统一为显示业务提示错误，无内容则显示网络请求出错了~
       * showAxiosErr=false处理逻辑
       * 1. 除401和403以外的错误不显示
       * 2. 401统一为操作权限错误
       * 3. 403统一为显示业务提示错误，无内容则显示网络请求出错了~
       */
      console.error("网络请求出错：", error);
      let response = error.response;
      let data = response?.data;
      //全部错误都需要显示
      if (response?.status === 401) {
        message.error(data?.error?.message || "没有操作权限！");
        const appStore = useAppStore();
        appStore.logout();
        router.replace("/login");
      } else if (response?.status === 404) {
        message.error("网络请求出错~");
      } else if (response?.status === 403) {
        message.error(data?.error?.message || "抱歉，你暂无此操作权限！");
      } else if (data && data.error) {
        message.error(data.error.message || "网络请求出错了~");
      }
      return Promise.reject(response);
    }
  );
};

export { useInterceptors };
